﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using NLBS.Data.Business;
using NLBS.Entity;
using NLBS.Framework;

namespace NLBS.Text
{
   public class LBSTextHelper
    {
        // Convert String to RegExp compatible -----------------------------------------------
        public static string stringToRegExp(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = new Regex(@"\\", RegexOptions.IgnoreCase).Replace(str, @"\");
            str = new Regex(@"\^", RegexOptions.IgnoreCase).Replace(str, @"\^");
            str = new Regex(@"\*", RegexOptions.IgnoreCase).Replace(str, @"\*");
            str = new Regex(@"\?", RegexOptions.IgnoreCase).Replace(str, @"\?");
            str = new Regex(@"\+", RegexOptions.IgnoreCase).Replace(str, @"\+");
            str = new Regex(@"\.", RegexOptions.IgnoreCase).Replace(str, @"\.");
            str = new Regex(@"\|", RegexOptions.IgnoreCase).Replace(str, @"\|");
            str = new Regex(@"\[", RegexOptions.IgnoreCase).Replace(str, @"\[");
            str = new Regex(@"\]", RegexOptions.IgnoreCase).Replace(str, @"\]");
            str = new Regex(@"\(", RegexOptions.IgnoreCase).Replace(str, @"\(");
            str = new Regex(@"\)", RegexOptions.IgnoreCase).Replace(str, @"\)");
            str = new Regex(@"\{", RegexOptions.IgnoreCase).Replace(str, @"\{");
            str = new Regex(@"\}", RegexOptions.IgnoreCase).Replace(str, @"\}");
            return str;
        }

        public static int StrLength(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }
            return Encoding.Default.GetBytes(str).Length;
        }

        public static string WordFilter(string str, out bool MathchResult)
        {
            MathchResult = true;
            if ((str == null) || (str == ""))
            {
                return "";
            }
            if (StrLength(str) >= 3)
            {
                List<WordFilter> table = WordFilterData.WordFilter;
                for (int i = 0; i < table.Count; i++)
                {
                    WordFilter wf = table[i];
                    string str2 = wf.Text.ToString();
                    if (str2 != "")
                    {
                        string pattern = wf.RegExp ? str2 : stringToRegExp(str2);
                        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                        if (Convert.ToBoolean(wf.Mode))
                        {
                            str = regex.Replace(str, wf.Replace);
                        }
                        else
                        {
                            Match match = regex.Match(pattern);
                            MathchResult = match.Success;
                            if (!MathchResult)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            return str;
        }

        public static string HighLight(string sContent, string[] Keywords)
        {
            if ((Keywords != null) && (Keywords.Length != 0))
            {
                for (int i = 0; i < Keywords.Length; i++)
                {
                    sContent = sContent.Replace(Keywords[i], "<span class=\"highlight\">" + Keywords[i] + "</span>");
                }
            }
            return sContent;
        }

        public static string CloseHTML(string str)
        {
            if (str == null)
            {
                return "";
            }
            string[] strArray = new string[] { 
        "p", "div", "span", "td", "th", "tr", "table", "li", "ol", "ul", "font", "b", "strong", "u", "i", "em", 
        "a", "h1", "h2", "h3", "h4", "h5", "h6", "label", "input", "option", "select", "textarea", "pre", "button", "iframe", "object", 
        "form", "script", "style"
     };
            for (int i = 0; i < strArray.Length; i++)
            {
                int count = 0;
                int num3 = 0;
                Regex regex = new Regex("<" + strArray[i] + "[^>]*>", RegexOptions.IgnoreCase);
                count = regex.Matches(str).Count;
                regex = new Regex("</" + strArray[i] + ">", RegexOptions.IgnoreCase);
                num3 = regex.Matches(str).Count;
                for (int j = 0; j < (count - num3); j++)
                {
                    str = str + "</" + strArray[i] + ">";
                }
            }
            return str;
        }

        public static string CutHtml(string str, int iLength)
        {
            if (str.Length > iLength)
            {
                str = str.Substring(0, iLength);
                if (str.LastIndexOf("<") > str.LastIndexOf(">"))
                {
                    str = str.Substring(0, str.LastIndexOf("<"));
                }
                str = CloseHTML(str + "...");
            }
            return str;
        }

        public static string lbsUBB(string str, string strFlags)
        {
            if (strFlags != "html")
            {
                string bBasic = strFlags.Substring(0, 1);
                string bAutoURL = strFlags.Substring(1, 1);
                string bImage = strFlags.Substring(2, 1);
                string bMedia = strFlags.Substring(3, 1);
                string bSmilies = strFlags.Substring(4, 1);
                string bTextBlock = strFlags.Substring(5, 1);
                str = Regex.Replace(str, @"\n", "<br/>");
                // Reverse the HTML Encode for New Line
                //str = Regex.Replace(str, @"/\<br \/\>/ig", "\n");
                str = Regex.Replace(str, @"/\&amp;nbsp;/ig", "&nbsp;");
                // Remove the content separator
                //str = Regex.Replace(str, @"/\[separator\]/ig", "");

                //str = Regex.Replace(str, @"[separator]", "<br/>");
                //

                if (bTextBlock == "1")
                {
                    //str = formatQuote(str, baseURL);
                    //str = formatCode(str);
                }
                if (bAutoURL == "1")
                {
                    //str = HtmlHelper.EnableUrls(str);
                }

                if (bBasic == "1")
                {
                str = BasicUBB(str);
                }



                // Process Smilies
                if (bSmilies == "1")
                {
                    str = SmilesToHTML(str);
                }
            }
            return str;
        }

        public static string SmilesToHTML(string content)
        {
            List<Smile> list = SmileData.GetSmile();
            string link = "<img src=\"{0}/{1}\" border=\"0\" alt=\"{2}\" />";
            string smilePath = BlogInfo.Instance().SmiliePath;
            if (smilePath.EndsWith("/"))
            {
                smilePath = smilePath.Substring(0, smilePath.Length - 1);
            }

            foreach (Smile item in list)
            {

                content = content.Replace(item.Code, string.Format(link, smilePath, item.Image, item.Code));
            }
            return content;
        }

        public static string BasicUBB(string detail)
        {
            Regex r;
            Match m;
            #region 处理[url][/url]标记
            //方法1 
            r = new Regex(@"(\[url\])([ \S\t]*?)(\[\/url\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(),
                    "<A href=\"" + m.Groups[2].ToString() + "\" target=\"_blank\">" +
                    m.Groups[2].ToString() + "</A>");
            }
            //方法2  
            detail = Regex.Replace(detail, @"\[URL\](?<x>[^\]]*)\[\/URL\]", @"<a href=$1 target=_blank>$1</a>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[center][/center]标记
            detail = Regex.Replace(detail, @"\[center\](?<x>[^\]]*)\[\/center\]", @"<div align=center>$1</div>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[color=xxx][/color]标记
            r = new Regex(@"(\[color=([\S]+)\])([ \S\t]*?)(\[\/color\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(),
                    "<FONT COLOR=" + m.Groups[2].ToString() + ">" +
                    m.Groups[3].ToString() + "</FONT>");
            }
            #endregion

            #region 处理[size=xxx][/size]标记
            r = new Regex(@"(\[size=([1-7])\])([ \S\t]*?)(\[\/size\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(),
                    "<FONT SIZE=" + m.Groups[2].ToString() + ">" +
                    m.Groups[3].ToString() + "</FONT>");
            }
            #endregion

            #region 处理[b][/b]标记
            //方法1 
            r = new Regex(@"(\[b\])([ \S\t]*?)(\[\/b\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<B>" + m.Groups[2].ToString() + "</B>");
            }
            //方法2 
            detail = Regex.Replace(detail, @"\[b\](?<x>[^\]]*)\[/b\]", @"<b>$1</b>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[i][/i]标记
            //方法1 
            r = new Regex(@"(\[i\])([ \S\t]*?)(\[\/i\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<I>" + m.Groups[2].ToString() + "</I>");
            }
            //方法2             
            detail = Regex.Replace(detail, @"\[i\](?<x>[^\]]*)\[/i\]", @"<i>$1</i>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[U][/U]标记
            //方法1 
            r = new Regex(@"(\[U\])([ \S\t]*?)(\[\/U\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<U>" + m.Groups[2].ToString() + "</U>");
            }
            //方法2         
            detail = Regex.Replace(detail, @"\[u\](?<x>[^\]]*)\[/u\]", @"<u>$1</u>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[U][/U]标记
            //方法1 
            r = new Regex(@"(\[S\])([ \S\t]*?)(\[\/S\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<s>" + m.Groups[2].ToString() + "</s>");
            }
            //方法2         
            detail = Regex.Replace(detail, @"\[s\](?<x>[^\]]*)\[/s\]", @"<s>$1</s>", RegexOptions.IgnoreCase);
            #endregion

            #region 处理[sup][/sup]标记
            r = new Regex(@"(\[sup\])([ \S\t]*?)(\[\/sup\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<SUP>" + m.Groups[2].ToString() + "</SUP>");
            }
            #endregion

            #region 处理[sub][/sub]标记
            r = new Regex(@"(\[sub\])([ \S\t]*?)(\[\/sub\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(), "<sub>" + m.Groups[2].ToString() + "</sub>");
            }
            #endregion

            #region 处理[list=xxx][/list]标记
            r = new Regex(@"(\[list(=(A|a|I|i| ))?\]([ \S\t]*)\r\n)((\[\*\]([ \S\t]*\r\n))*?)(\[\/list\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                string strLI = m.Groups[5].ToString();
                Regex rLI = new Regex(@"\[\*\]([ \S\t]*\r\n?)", RegexOptions.IgnoreCase);
                Match mLI;
                for (mLI = rLI.Match(strLI); mLI.Success; mLI = mLI.NextMatch())
                {
                    strLI = strLI.Replace(mLI.Groups[0].ToString(), "<LI>" + mLI.Groups[1]);
                }
                detail = detail.Replace(m.Groups[0].ToString(),
                    "<UL TYPE=\"" + m.Groups[3].ToString() + "\"><B>" + m.Groups[4].ToString() + "</B>" +
                    strLI + "</UL>");
            }
            //unknown 
            //            detail = Regex.Replace(detail,@"\[list\](?<x>[^\]]*)\[/list\]",@"<ul>$1</ul>",RegexOptions.IgnoreCase);  
            //            detail = Regex.Replace(detail,@"\[list=1\](?<x>[^\]]*)\[/list\]",@"<ol type=1>$1</ol id=1>",RegexOptions.IgnoreCase);          
            //            detail = Regex.Replace(detail,@"\[list=a\](?<x>[^\]]*)\[/list\]",@"<ol type=a>$1</ol id=a>",RegexOptions.IgnoreCase);              
            //            detail = Regex.Replace(detail,@"\[\*\](?<x>[^\]]*)\[/\*\]",@"<li>$1</li>",RegexOptions.IgnoreCase);  
            #endregion

            #region 处理[quote=xxx][/quote]标记
            r = new Regex(@"(\[quote=([\S]+)\])([ \S\t]*?)(\[\/quote\])", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(),
                    string.Format("<div class=\"quote\"><div class=\"quote-title\">引用至 <u>{0}</u></div><div class=\"quote-content\">{1}</div></div>",
                     m.Groups[2].ToString(),
                      m.Groups[3].ToString())
                    );
            }
            #endregion

            #region [file=xxx][/file]

            r = new Regex(@"(\[file=([\S]+)\])([ \S\t]*?)(\[\/file\])", RegexOptions.IgnoreCase);
            string a="<a href=\"{0}\" title=\"{0}\" target=\"_blank\"><img src=\"\" border=\"0\" />点击下载</a>";
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                detail = detail.Replace(m.Groups[0].ToString(),
                    string.Format("<a href=\"{0}\" title=\"{0}\" target=\"_blank\"><img src=\"/styles/default/images/icon_file.gif\" border=\"0\" />点击下载</a>", m.Groups[2].ToString()));
            }

            #endregion

            #region [swf=xxx][/swf]

            //r = new Regex(@"(\[swf=([\S]+)\])([ \S\t]*?)(\[\/swf\])", RegexOptions.IgnoreCase);

            //for (m = r.Match(detail); m.Success; m = m.NextMatch())
            //{
            //    StringBuilder sb = new StringBuilder();
            //    sb.Append("<div class=\"ubb-obj-div\">");
            //    Guid newobj = Guid.NewGuid();
            //    sb.AppendFormat("<input id=\"bShow{0}\" type=\"hidden\" value=\"-1\"/>", newobj);
            //    sb.AppendFormat("<a href=\"javascript:ubbShowObj('swf','{0}','{1}','400','300');\">", newobj, m.Groups[2].ToString());
            //    sb.Append("<img alt=\"Media\" src=\"styles/default/images/icon_media.gif\"/><b>点此显示/隐藏媒体</b></a>");
            //    sb.AppendFormat("<div id=\"{0}\"></div>", newobj);
            //    sb.Append("</div>");
            //    detail = detail.Replace(m.Groups[0].ToString(), sb.ToString());
            //}

            r = new Regex(@"\[swf\](?<x>[^\]]*)\[\/swf\]", RegexOptions.IgnoreCase);
            for (m = r.Match(detail); m.Success; m = m.NextMatch())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<div class=\"ubb-obj-div\">");
                Guid newobj = Guid.NewGuid();
                sb.AppendFormat("<input id=\"bShow{0}\" type=\"hidden\" value=\"-1\"/>", newobj);
                sb.AppendFormat("<a href=\"javascript:ubbShowObj('swf','{0}','{1}','400','300');\">", newobj, m.Groups[2].ToString());
                sb.Append("<img alt=\"Media\" src=\"styles/default/images/icon_media.gif\"/><b>点此显示/隐藏媒体</b></a>");
                sb.AppendFormat("<div id=\"{0}\"></div>", newobj);
                sb.Append("</div>");
                detail = detail.Replace(m.Groups[0].ToString(), sb.ToString());
            }

            #endregion

            #region 处理[IMG][/IMG]标记
            detail = Regex.Replace(detail, @"\[IMG\](?<x>[^\]]*)\[\/IMG\]", @"<IMG SRC=""$1"" border=0>", RegexOptions.IgnoreCase);
            #endregion 


            return detail;
        }


       public static string formatQuote(string str,string baseURL)
       {
           return string.Empty;
       }

       public static string formatCode(string str)
       {
           return string.Empty;
       }


       // Process [quote] tag ////////////////////////////////////////////////////
//  public static string formatQuote(string str,string baseURL)
//  {
//    str=Regex.Replace(str, @"/\[quote\]/ig","[quote=]");
//    // Clean up string
//    str=Regex.Replace(str, @"/\[quote=/ig","[quote=");
//    str=Regex.Replace(str, @"/\[\/quote\]/ig","[/quote]");
//    str=Regex.Replace(str, @"/\n*\[quote=/ig","[quote=");
//    str=Regex.Replace(str, @"/\n*\[\/quote\]/ig","[/quote]");
//    str=Regex.Replace(str, @"/\[quote=([^]]*)]\n*/ig","[quote=$1]");
//    str=Regex.Replace(str, @"/\[\/quote\]\n*/ig","[/quote]");

//    while(str.IndexOf("[quote=", 0)>-1 && str.IndexOf("[/quote]", 0)>-1){
//      int intStart,intEnd;
//      string strText="";
//      string strAuthor="";
//      string strResult="";
//      string strSource="";
//      intStart = str.IndexOf("[quote=", 0) + 7;
//      intEnd = str.IndexOf("]",intStart);
//      if(intStart>6 && intEnd>0){
//        strAuthor = str.substr(intStart, intEnd-intStart);
//      }
//      intStart = intStart + strAuthor.length + 1;
//      intEnd = str.IndexOf("[/quote]",intStart);
//      if(intEnd<=intStart) intEnd = intStart;
//      if(intEnd>intStart){
//        strText = str.substr(intStart, intEnd-intStart);
//        //string strAuthorText =Regex.Replace(strAuthor,@"/\"/g, "");
//        string quoteText = strAuthorText.Length>1 ? lang["quote_from"] : lang["quote"];
//        strResult = "<div class=\"quote\"><div class=\"quote-title\">"+quoteText+"<u>" + strAuthorText + "</u></div><div class=\"quote-content\">" + this.toHTML(strText,"102201",baseURL) + "</div></div>";
//      }
//      intStart = str.IndexOf("[quote=", 0);
//      intEnd = str.IndexOf("[/quote]", intStart) + 8;
//      if(intEnd<=intStart+7) intEnd = intStart + strAuthor.length + 8;
//      strSource = str.substr(intStart, intEnd-intStart);
//      if(strResult!=""){
//        str = Regex.Replace(str, @"strSource, strResult);
//      }else{
//        str = Regex.Replace(str, @"strSource, strSource.replace(/\[/g, "&#91;"));
//      }
//    }
//    str=Regex.Replace(str, @"/quote\=\\]/ig,"quote]");
//    return str;
//  }

        

    }
}
